package cn.virens.service.impl.web;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.io.FileUtil;
import cn.virens.CacheKeys;
import cn.virens.components.page.PageParamUser;
import cn.virens.database.common.BaseServiceImpl;
import cn.virens.database.common.mapper.ExampleJoin;
import cn.virens.database.common.mapper.ExampleWrapper;
import cn.virens.database.mysql.mapper.web.WebPageMapper;
import cn.virens.database.mysql.model.web.WebPage;
import cn.virens.exception.APIException;
import cn.virens.service.inter.web.WebPageService;
import cn.virens.utils.PermissionUtil;

/**
 * 静态活动页 - web_page
 *
 * @author Virens
 * @since  2018-08-25 15:36:58
 */
@Service
public class WebPageServiceImpl extends BaseServiceImpl<WebPageMapper, WebPage> implements WebPageService {

	public WebPageServiceImpl() {
		super(WebPage.class);
	}

	@Override
	@Transactional(readOnly = true)
	@Cacheable(value = CacheKeys.WEB_PAGE, key = "#p0", unless = "#result == null")
	public WebPage selectOne(Serializable code) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andEqualTo("code", code);

		return mBaseMapper.selectOne(example);
	}

	@Override
	@Transactional(readOnly = false)
	@CacheEvict(value = CacheKeys.WEB_PAGE, key = "#p0")
	public int delete(String rootPath, String... codes) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andIn("code", Arrays.asList(codes));

		// 删除物理文件
		for (WebPage item : mBaseMapper.selectByExample(example)) {
			FileUtil.del(item.getPath(rootPath));
		}

		// 删除数据库文件
		return mBaseMapper.deleteByExample(example);
	}

	@Override
	protected List<?> doPageQuery(PageParamUser param) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.selectProperties("web_page.id", "web_page.`code`", "web_page.`name`", "web_page.path", "web_page.res_group");
		example.selectProperties("web_page.create_time", "web_page.update_time", "sys_user_group.`name` AS res_groupn");

		example.addJoinTable(ExampleJoin.left("sys_user_group", "sys_user_group.identity = web_page.res_group"));

		if (param != null && !PermissionUtil.isCanViewAllData(param)) {
			example.and().andCondition(PermissionUtil.str(param, "web_page."));
		}

		return mBaseMapper.selectJoinMap(example);
	}

	@Override
	public int delete(Serializable... id) {
		throw new APIException("DISABLE_API", "Disable create the resource!");
	}

	@Override
	public WebPage update(WebPage record) {
		throw new APIException("DISABLE_API", "Disable create the resource!");
	}
}
